<template>
  <div class="expense-add">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">报销提交</div>
      </div>
    </div>
    <!-- 表单内容 -->
    <div class="form-container">
      <!-- 报销金额--展示 -->
      <div class="form-field amount-field">
        <div class="amount-container">
          <div>
            <div class="amount-container-label">报销金额</div>
            <div class="amount-display">{{ formData.amount || "0.00" }}</div>
          </div>
          <img
            src="@/assets/homeOther/pay_detial_icon.png"
            alt="金额图标"
            class="amount-icon"
          />
        </div>
      </div>
      <div class="expense-detail-title">报销明细</div>
      <!-- form表单金额 -->
      <div class="form-field">
        <div class="field-label">报销金额</div>
        <van-field
          v-model="formData.amount"
          placeholder="请输入"
          type="number"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>

      <!-- 文件上传组件（使用 Vant Uploader 封装） -->
      <div class="form-field uploader-field">
        <!-- 顶部一行：左侧文案+右侧加号 -->
        <div class="uploader-header" @click="openUploaderInput($event)">
          <div class="field-label">报销凭证</div>
          <button
            type="button"
            class="list-upload-btn"
            aria-label="添加附件"
            @click.stop="openUploaderInput($event)"
          >
            <van-icon name="add-o" class="list-upload-btn__icon" />
          </button>
        </div>
        <!-- 下方列表：只显示预览列表，隐藏内部的上传加号 -->
        <VantUploader
          ref="uploaderCompRef"
          v-model="fileList"
          :max-file-count="5"
          :max-file-size-m-b="10"
          :show-upload-button="false"
        />
      </div>

      <!-- 其他现有表单字段保持不变 -->
      <!-- 费用发生日期 -->
      <div class="form-field">
        <div class="field-label">费用发生日期</div>
        <van-field
          v-model="formData.expenseDate"
          is-link
          readonly
          placeholder="请选择"
          @click="showExpenseDatePicker = true"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>
      <!-- 报销类型 -->
      <div class="form-field">
        <div class="field-label">报销类型</div>
        <van-field
          v-model="formData.expenseTypeText"
          is-link
          readonly
          placeholder="请选择"
          @click="showExpenseTypeSelector"
          :border="false"
          class="custom-field"
          autocomplete="off"
        />
      </div>


      <!-- 费用明细 -->
      <div class="form-field textarea-field">
        <div class="field-label">报销明细</div>
        <van-field
          v-model="formData.expenseDetail"
          placeholder="请输入费用明细描述"
          type="textarea"
          rows="3"
          :border="false"
          class="custom-field"
          maxlength="2000"
          show-word-limit
          autocomplete="off"
        />
      </div>

      <!-- 流程步骤 -->
      <div class="form-container">
        <div class="process-step-container">
          <div class="process-step-title">流程</div>
          <div class="process-steps">
            <div
              v-for="(step, index) in approvalSteps"
              :key="index"
              class="process-step"
              :class="{ 'is-last': index === approvalSteps.length - 1 }"
            >
              <!-- 左侧步骤条 -->
              <div class="step-line-container">
                <div class="step-dot"></div>
                <div
                  v-if="index < approvalSteps.length - 1"
                  class="step-line"
                ></div>
              </div>

              <!-- 右侧人员信息 -->
              <div class="step-info">
                <div class="step-title-container">
                  <div class="step-title">{{ step.title }}</div>
                  <div v-if="step.subtitle" class="step-subtitle">
                    {{ step.subtitle }}
                  </div>
                </div>
                <div class="step-person">
                  <div class="person-avatar">
                    <AvatarDisplay :url="step.url" :name="step.name" />
                  </div>
                  <div class="person-name">{{ step.name }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="action-buttons">
        <van-button 
          class="action-btn submit-btn" 
          :disabled="submitting" 
          :loading="submitting && approvalSteps.length > 0"
          @click="submitExpense"
        >
          提交
        </van-button>
      </div>
    </div>
  </div>

  <!-- 报销类型选择 -->
  <van-action-sheet
    v-model:show="showExpenseTypeSheet"
    :actions="expenseTypeActions"
    title="选择报销类型"
    @select="onExpenseTypeSelect"
    cancel-text="取消"
  />

  <!-- 报销类型选择 -->
  <van-action-sheet
    v-model:show="showReimbursementTypeSheet"
    :actions="reimbursementTypeActions"
    title="选择报销类型"
    @select="onReimbursementTypeSelect"
    cancel-text="取消"
  />

  <!-- 费用发生日期选择器 -->
  <van-popup v-model:show="showExpenseDatePicker" position="bottom">
    <van-date-picker
      title="选择费用发生日期"
      v-model="expenseDateArray"
      @confirm="onExpenseDateConfirm"
      @cancel="showExpenseDatePicker = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { useRouter, onBeforeRouteLeave } from "vue-router";
import { showToast } from "vant";
import { expenseTypeOptions, reimbursementTypeOptions } from "@/utils/enums";
import { addBaoXiao } from "@/api/expense";
import { queryFlow, getUserPicture } from "@/api/contract";
import pictureImg from "@/assets/homeOther/picture.png";
import pictureOneImg from "@/assets/homeOther/sm_picture.png";
import pictureTwoImg from "@/assets/homeOther/picture_two.png";
import AvatarDisplay from '@/components/UserAvatar/AvatarDisplay.vue';
import { navigateAfterSubmit, smartGoBack } from '@/utils/navigation';
import VantUploader from '@/components/UploadFiled/VantUploader.vue';
import { openUploadFromRowClick } from '@/utils/uploadTrigger';
import { useHardwareBackCleanup } from '@/utils/hardwareBackCleanup';
defineOptions({ name: 'ExpenseAdd' })

const router = useRouter();

// 让整行（含标签）都能触发上传：点击时主动触发内部 input[type=file]
const uploaderCompRef = ref(null);
  const openUploaderInput = (e) => {
    openUploadFromRowClick(e, uploaderCompRef.value);
  };

// 重置新增报销页状态
const resetExpenseAddState = () => {
  // 清空表单数据
  formData.amount = '';
  formData.expenseType = '';
  formData.expenseTypeText = '';
  formData.expenseDate = '';
  formData.reimbursementType = '';
  formData.reimbursementTypeText = '';
  formData.expenseDetail = '';
  
  // 清空附件
  fileList.value = [];
  uploadedFiles.value = '';
  
  // 关闭选择器开关
  showExpenseTypeSheet.value = false;
  showReimbursementTypeSheet.value = false;
  showExpenseDatePicker.value = false;
  
  // 重置审批步骤
  approvalSteps.value = [];
  submitting.value = false;
  
  // 重置日期选择器数组
  expenseDateArray.value = getCurrentDateArray();
};

// 绑定手机系统返回（popstate）时的清理逻辑
useHardwareBackCleanup('ExpenseAdd', resetExpenseAddState);

// 返回上一页
const goBack = () => {
  // 先重置本地状态
  resetExpenseAddState();
  // 再清除本页的 KeepAlive 缓存
  window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ExpenseAdd' } }));
  // 统一返回逻辑
  smartGoBack(router);
};

// 提交状态
const submitting = ref(false);

// 表单数据
const formData = reactive({
  amount: "",
  expenseType: "",
  expenseTypeText: "",
  expenseDate: "",
  reimbursementType: "",
  reimbursementTypeText: "",
  expenseDetail: "",
});

// 流程步骤数据
const approvalSteps = ref([]);

// 获取姓名后两位字符作为头像
const getNameInitials = (name) => {
  if (!name) return '';
  return name.length >= 2 ? name.slice(-2) : name;
};

// 获取当前日期数组格式
const getCurrentDateArray = () => {
  const now = new Date();
  const year = now.getFullYear().toString();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  return [year, month, day];
};

// 选择器显示状态
const showExpenseTypeSheet = ref(false);
const showReimbursementTypeSheet = ref(false);
const showExpenseDatePicker = ref(false);

// 日期选择器数组变量
const expenseDateArray = ref(getCurrentDateArray());

// 使用公共枚举选项
const expenseTypeActions = expenseTypeOptions;
const reimbursementTypeActions = reimbursementTypeOptions;

// 显示报销类型选择器
const showExpenseTypeSelector = () => {
  showExpenseTypeSheet.value = true;
};

// 显示报销类型选择器
const showReimbursementTypeSelector = () => {
  showReimbursementTypeSheet.value = true;
};

// 报销类型选择
const onExpenseTypeSelect = (action) => {
  formData.expenseType = action.value;
  formData.expenseTypeText = action.name;
  showExpenseTypeSheet.value = false;
};

// 报销类型选择
const onReimbursementTypeSelect = (action) => {
  formData.reimbursementType = action.value;
  formData.reimbursementTypeText = action.name;
  showReimbursementTypeSheet.value = false;
};

// 费用发生日期确认
const onExpenseDateConfirm = ({ selectedValues }) => {
  const [year, month, day] = selectedValues;
  formData.expenseDate = `${year}-${month.toString().padStart(2, "0")}-${day
    .toString()
    .padStart(2, "0")}`;
  showExpenseDatePicker.value = false;
};

// 加载用户头像
const loadUserAvatar = async (url) => {
  if (!url) return 'text'; // 返回标识符表示使用文字头像
  
  try {
    const blob = await getUserPicture(url);
    return URL.createObjectURL(blob);
  } catch (error) {
    console.error('加载头像失败:', error);
    return 'text'; // 加载失败时使用文字头像
  }
};

// 查询流程信息
const loadFlowData = async () => {
  try {
    const response = await queryFlow();
    
    if (response.code === 0 && response.data) {
      const { firstApprover, secondApprover, thirdApprover } = response.data;
      
      // 收集所有有效的审批人
      const approvers = [];
      
      if (firstApprover && Object.keys(firstApprover).length > 0) {
        approvers.push(firstApprover);
      }
      
      if (secondApprover && Object.keys(secondApprover).length > 0) {
        approvers.push(secondApprover);
      }
      
      if (thirdApprover && Object.keys(thirdApprover).length > 0) {
        approvers.push(thirdApprover);
      }
      
      // 检查是否有审批人
      if (approvers.length === 0 || approvers.length === 1) {
        // Toast提示并禁用提交按钮
        showToast('该公司尚未设置CEO或组织架构尚未完善');
        submitting.value = true; // 禁用提交按钮
        return;
      }
      
      // 动态构建审批步骤数组，级别从1开始
      const steps = [];
      
      for (let i = 0; i < approvers.length; i++) {
        const approver = approvers[i];
        const avatar = await loadUserAvatar(approver.url);
        steps.push({
          title: "审批人",
          subtitle: `${i + 1}级审批`,
          name: approver.name,
          avatar: avatar,
          url: approver.url,
          id: approver.id
        });
      }
      
      // 更新审批步骤
      approvalSteps.value = steps;
    }
  } catch (error) {
    console.error('查询流程失败:', error);
    showToast('加载流程信息失败');
  }
};

// 使用 Vant Uploader 的文件列表
const fileList = ref([]);
// 统一的附件字符串（以逗号拼接的服务器路径）
const uploadedFiles = ref("");

// 同步 fileList 到附件字符串
watch(
  fileList,
  (list) => {
    const paths = (list || [])
      .map((f) => f.serverPath)
      .filter(Boolean)
      .join(',');
    uploadedFiles.value = paths;
    console.log('文件列表已更新:', uploadedFiles.value);
  },
  { deep: true }
);

// 修改提交报销函数，添加文件相关数据
const submitExpense = async () => {
  // 表单验证 - 必填项校验
  if (!formData.amount || formData.amount <= 0) {
    showToast("请输入有效的报销金额");
    return;
  }
  if (!formData.expenseDate) {
    showToast("请选择费用发生日期");
    return;
  }
  if (!formData.expenseTypeText) {
    showToast("请选择报销类型");
    return;
  }

  // 验证是否上传了凭证
  if (!uploadedFiles.value || uploadedFiles.value === '') {
    showToast("请上传报销凭证");
    return;
  }

  try {
    submitting.value = true;

    // 构建API请求参数
    const requestData = {
      amount: parseFloat(formData.amount), // 确保金额为数字类型
      amountDate: formData.expenseDate, // 费用发生日期
      amountType: formData.expenseType, // 报销类型值
      amountRemark: formData.expenseDetail, // 报销明细作为备注
      // 添加文件相关数据 - 现在直接使用字符串格式
      attachmentUrl: uploadedFiles.value
    };

    // 调用报销申请接口
    const response = await addBaoXiao(requestData);
    
    if (response.code === 0) {
      showToast({ type: 'success', message: response.msg || "报销申请提交成功" });
      
      // 提交成功后先重置本地状态
      resetExpenseAddState();
      
      // 再清理本页缓存
      window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ExpenseAdd' } }));
      
      // 使用统一的导航工具函数处理跳转
      navigateAfterSubmit(router, response);
    } else {
      showToast(response.msg || "提交失败，请重试");
    }
  } catch (error) {
    console.error('提交报销申请失败:', error);
    showToast("提交失败，请重试");
  } finally {
    submitting.value = false;
  }
};

// 组件挂载时加载流程数据
onMounted(() => {
  loadFlowData();
});

// 页面离开时的统一清理：
// - 前往附件预览（/file-preview*）或组织架构（/organization*）时保留数据；
// - 其它任何离开（包括系统返回/左滑、跳转详情等）一律清理，确保各端一致。
onBeforeRouteLeave((to) => {
  try {
    const destPath = to?.path || '';
    const goingToPreview = destPath.startsWith('/file-preview');
    const goingToOrganization = destPath.startsWith('/organization');

    if (goingToPreview || goingToOrganization) {
      return; // 不清理，保持表单与附件
    }

    resetExpenseAddState();
    window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ExpenseAdd' } }));
  } catch (err) {
    console.warn('[ExpenseAdd] onBeforeRouteLeave cleanup failed:', err);
  }
});
</script>

<style lang="scss" scoped>
@import url("./style/add.scss");

/* 垂直居中“报销凭证”与右侧上传按钮 */
.form-field.uploader-field {
  position: relative;          /* 容器用于内部布局 */
  display: block;              /* 顶部一行 + 下方列表 */
  cursor: pointer;

  /* 顶部一行：左侧文案 + 右侧加号 */
  .uploader-header {
    display: flex;
    align-items: center;
    min-height: 50px;
  }
  .field-label {
    padding-bottom: 0;
  }
  .list-upload-btn {
    margin-left: auto;
    width: 50px;
    height: 50px;
    border: none;
    background: transparent;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .list-upload-btn__icon {
  color: #dcdee0;
    font-size: 50px !important;
    font-weight: 800;
  }

  /* 去掉默认外边距，避免上下不居中 */
  ::v-deep(.van-uploader) {
    margin: 0;
    padding: 0;
    display: block;        /* 让预览列表作为块级元素显示在标签下方 */
    width: 100%;
    margin-top: 8px;       /* 与顶部标签行留出间距 */
  }

  /* 上传加号图标大小与粗细 */
  ::v-deep(.van-uploader__upload-icon),
  ::v-deep(.van-uploader__upload .van-icon) {
    font-size: 50px !important;
    font-weight: 800 !important;
  }
}
</style>